from scapy.all import *
import gmssl.sm3 as sm3
import time


from scapy.layers.inet import TCP,IP


def chk_sum(a):
    b = str(a)
    length=len(b)
    if len(b) % 2 != 0:
        b += "0"
    ans_list = []
    for i in range(int(len(b) / 2)):
        temp = b[i * 2:i * 2 + 2].encode('utf-8')

        ans_list.append(sm3.sm3_kdf(temp, 1))
    ans = ""
    for i in ans_list:
        for j in range(2):
            temp2 = str(i[j])

            list=['a','b','c','d','e','f']
            if temp2 in list:
                temp2=str(list.index(temp2))
            ans+=temp2
    return ans


def send_pkt(num,key):
    if num < int(len(key) * 8 / 3) + 2:
        print("信息长度过长，请减少信息长度或增加数据包的数量")
    else:
        data= 'GET www.testforyyf.com\r\nHost: www.google.com\r\nX-id: Wget/1.12 (linux-gnu)\r\n\r\n'
        a=852353
        b=12315
        list=[]
        pkt_list=[]
        for i in range(num):
            a+=20
            b+=1
            pkt=IP(src='192.168.188.66',dst='192.168.188.90')/TCP(sport=b,dport=80,seq=a,ack=int(chk_sum(a)))/data
            pkt_list.append(pkt)
        a+=20
        b+=1
        pkt_end = pkt = IP(src='192.168.188.66', dst='192.168.188.90') / TCP(sport=b, dport=80, seq=a,
                                                                     ack=int(chk_sum(b))) / data
        time2=time_get(key)
        for i in pkt_list:
            send(i,iface="Intel(R) Wireless-AC 9560 160MHz")
            if pkt_list.index(i)<len(time2):
                time.sleep(time2[pkt_list.index(i)])
            else:
                time.sleep(1)
        else:
            send(pkt_end,iface="Intel(R) Wireless-AC 9560 160MHz")
        # list.append(random.randint(1, 30) / 10)


def get_ascii(a):
    ans = ""
    for i in range(len(a)):
        b = bin(int(str(ord(a[i])), 10))
        temp = 8 - len(b[2:])
        for i in range(temp):
            ans += '0'
        ans += b[2:]
    print(ans)
    return ans


def time_get(key):
    a=[]
    pool = ['000','001','010','011','100','101','110','111']
    time_pool=[1,2,3,4,5,6,7,8]
    aim=get_ascii(key)
    time=[]
    if len(aim) % 3 == 0:
        for i in range(int(len(aim)/3)):
            time.append(time_pool[pool.index(aim[i*3:i*3+3])])
        return time
    else:
        for i in range(3-len(aim)%3):
            aim += '0'
        for i in range(int(len(aim)/3)):
            time.append(time_pool[pool.index(aim[i*3:i*3+3])])
        print(time)
        return time



send_pkt(23,"password")